package com.tqz.juc.jmm;

/**
 * <p>JMM内存模型原子性测试
 *
 * @author tianqingzhao
 * @since 2022/1/15 16:33
 */
public class JavaMemoryModelAtomicTest {
    
    private volatile static int counter = 0;
    
    static Object object = new Object();
    
    public static void main(String[] args) {
        
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    synchronized (object) {
                        // 分三步- 读，自加，写回
                        // 这三步每一步都是原子的，但是分开就不是了
                        // 需要加上 `synchronized` 关键字保证原子性
                        counter++;
                    }
                }
            });
            thread.start();
        }
        
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println(counter);
        
    }
}
